/** 
 * @author hannz
 * content:user
 * creatTime:2023年7月14日13:53:57
 * 
  */
const user = require('../db/model/user')
const express = require("express");
const login = express.Router();
const { check, body, validationResult } = require('express-validator')
const jwt = require('jsonwebtoken');
const SECRET_KEY = 'hannz'
const { Op } = require("sequelize");
/**
 * @swagger
 * /api/user/login:
 *   get:
 *     tags:
 *       - 登录
 *     description: login
 *     security:
 *      - CoreAPI: []
 *     parameters:
 *            - name: account 
 *              in: query
 *              description: 用户账号
 *              required: true
 *              schema:
 *                  type: string
 *                  default: null
 *            - name: passWord 
 *              in: query
 *              description: 用户密码
 *              required: true
 *              schema:
 *                  type: string
 *                  default: null                 
 *     responses:
 *       200:
 *         description: 登录成功！
 *
 */
login.get('/login', [
    check('account', '账号不能为空').notEmpty(),
    check('passWord', '密码不能为空').notEmpty(),
], (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.json({
            status: 405,
            message: '请检查参数是否合法！',
            data: errors.array()
        })
    }
    const { account, passWord } = req.query
    const token = jwt.sign(
        { user: { account, passWord } },
        SECRET_KEY,
        { expiresIn: '3h' }
    )
    user.findAll({
        where: {
            account,
        }
    }).then(data => {
        console.log(data);
        if (data.length == 0) {
            res.send({
                status: 202,
                message: '该账号未注册！请先注册！'
            })
        } else {
            if (data[0].passWord != passWord) {
                return res.send({
                    status: 202,
                    message: '密码错误！'
                })
            }
            res.send({
                status: 200,
                data: data[0],
                accessToken: token,
                message: '登录成功！'
            })
        }
    })

})
/**
 * @swagger
 * /api/user/register:
 *   post:
 *     tags:
 *       - 注册
 *     description: 注册
 *     security:
 *      - CoreAPI: []
 *     consumes:
 *     - "application/json"
 *     requestBody:
 *       required: true
 *       content:
 *          application/json:
 *              schema:
 *                  type: object
 *                  properties:
 *                      account:
 *                          type:string
 *                          description:账号
 *                      passWord:
 *                          type:string
 *                          description:密码
 *                      userName:
 *                          type:string
 *                          description:昵称
 *                      
 *              example:        #请求参数样例。
 *                      account: akaNum
 *                      userName: "lebornJames"
 *                      passWord: "123456"
 *          
 *                          
 *     responses:
 *       200:
 *         description: 添加成功
 *
 */
login.post('/register', [
    check('account', '账号不能为空').notEmpty(),
    check('userName', '昵称不能为空').notEmpty(),
    check('passWord', '密码不能为空').notEmpty(),
], (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.json({
            status: 405,
            message: '参数错误',
            data: errors.array()
        })
    }
    const { account, userName, passWord } = req.body
    const ipInfo = req.ipInfo;
    console.log(ipInfo);
    user.findAll({
        where: {
            account
        }
    }).then(data => {
        if (data.length > 0) {
            res.json({
                status: 202,
                message: '该账号已注册！',
            })
        } else {
            user.create({
                account,
                passWord,
                userName,
                ip:`${ipInfo.country} ${ipInfo.city} ${ipInfo.ip}`,
                isBanned: 0,
                create_time: new Date()
            }).then(user => {
                res.json({
                    status: 200,
                    message: '注册成功！',
                })
            })
                .catch(err => {
                    console.error('Error creating user:', err);
                });
        }
    })
})
/**
 * @swagger
 * /api/user/getAllUser:
 *   get:
 *     tags:
 *       - 用户
 *     description: 获取用户
 *     security:
 *      - CoreAPI: []        
 *     responses:
 *       200:
 *         description: 获取成功
 *
 */
login.get('/getAllUser', (req, res) => {
    user.findAll().then(data => {
        res.json({
            status: 200,
            message: '',
            data
        })
    })
})
/**
 * @swagger
 * /api/user/getUserById:
 *   get:
 *     tags:
 *       - 用户
 *     description: 通过id搜索
 *     security:
 *      - CoreAPI: []
 *     parameters:
 *            - name: id 
 *              in: query
 *              description: 用户id
 *              required: true
 *              schema:
 *                  type: string
 *                  default: null               
 *     responses:
 *       200:
 *         description: success
 *
 */
login.get('/getUserById', (req, res) => {
    const { id } = req.query
    user.findByPk(id)
        .then(data => {
            console.log(data);
            res.json({
                status: 200,
                data,
                message: 'success',

            })
        }).catch(err => {
            res.json({
                status: 403,
                message: '系统错误',

            })
        })

})
/**
 * @swagger
 * /api/user/editUserById:
 *   post:
 *     tags:
 *       - 用户
 *     description: 修改用户
 *     security:
 *      - CoreAPI: []
 *     consumes:
 *     - "application/json"
 *     requestBody:
 *       required: true
 *       content:
 *          application/json:
 *              schema:
 *                  type: object
 *                  properties:
 *                      id:
 *                          type:number
 *                          description:id
 *                      account:
 *                          type:string
 *                          description:账号
 *                      passWord:
 *                          type:string
 *                          description:密码
 *                      userName:
 *                          type:string
 *                          description:昵称
 *                      isBanned:
 *                          type:number
 *                          description:是否黑名单
 *                      
 *              example:        #请求参数样例。
 *                      account: 222
 *                      userName: "lebornJames3232"
 *                      passWord: "123456"
 *                      id: 1
 *                      isBanned: 0
 *                          
 *     responses:
 *       200:
 *         description: 添加成功
 *
 */
login.post('/editUserById', (req, res) => {
    const { id } = req.body
    user.findByPk(id)
        .then(data => {
            if (data != null) {
                user.update(req.body, {
                    where: {
                        id
                    }
                })
                    .then(data2 => {
                        res.json({
                            status: 200,
                            message: '修改成功！',
                        })
                    })
            } else {
                res.json({
                    status: 403,
                    message: 'id错误',
                })
            }

        })

})
/**
 * @swagger
 * /api/user/delUserById:
 *   post:
 *     tags:
 *       - 用户
 *     description: 删除用户
 *     security:
 *      - CoreAPI: []
 *     consumes:
 *     - "application/json"
 *     requestBody:
 *       required: true
 *       content:
 *          application/json:
 *              schema:
 *                  type: object
 *                  properties:
 *                      id:
 *                          type:number
 *                          description:id
 *                      
 *              example:        #请求参数样例。
 *                      id: 
 *                          
 *     responses:
 *       200:
 *         description: 删除成功
 *
 */
login.post('/delUserById', (req, res) => {
    const { id } = req.body
    user.findByPk(id)
        .then(data => {
            if (data != null) {
                user.destroy({
                    where: {
                        id
                    }
                })
                    .then(data2 => {
                        res.json({
                            status: 200,
                            message: '删除成功！',
                        })
                    })
            } else {
                res.json({
                    status: 403,
                    message: 'id错误',
                })
            }

        })
})
/**
 * @swagger
 * /api/user/searchUsers:
 *   get:
 *     tags:
 *       - 用户
 *     description: 多条件模糊搜索user
 *     security:
 *      - CoreAPI: []
 *     consumes:
 *     - "application/json"
 *     parameters:
 *            - name: account 
 *              in: query
 *              description: 用户账号
 *              required: false
 *              schema:
 *                  type: string
 *                  default: null
 *            - name: userName 
 *              in: query
 *              description: 用户昵称
 *              required: false
 *              schema:
 *                  type: string
 *                  default: null    
 *            - name: isBanned 
 *              in: query
 *              description: 是否黑名单
 *              required: false
 *              schema:
 *                  type: number
 *                  default: null                  
 *     responses:
 *       200:
 *         description: 添加成功
 *
 */
login.get('/searchUsers', (req, res) => {
    let arr = []
    console.log(req.query,'params');
    for (var key in req.query) {
        let obj = {}
        obj[key] = { [Op.like]: `%${req.query[key]}%` }
        if (obj[key] != null) {
            arr.push(obj)
        }
    }
    console.log(arr);
    user.findAll({
        where: {
            [Op.and]: arr
        }
    }).then(data => {
        res.json({
            status: 200,
            message: '查询成功！',
            data
        })
    })
})
module.exports = login